0.1.5Updated 6 months ago
import State from "@infinity-beyond/modules/state.ts";
import { plural } from "https://deno.land/x/deno_plural@2.0.0/mod.ts";
import type { Handlers, PageProps } from "$fresh/server.ts";

import { Ledger } from "@ledger/mod.ts";
import { Supply } from "@supply/supply.ts";
import { LedgerTableData } from "@ledger/ledger.ui/ledger.table.data.tsx";
import type { I_Pagination } from "@infinity-beyond/modules/pagination.ts";
import { LedgerTable } from "@ledger/ledger.ui/LedgerTable.tsx";

export const handler: Handlers<I_EntityScreen> = {
  async GET(request, ctx) {
    const entity_slug = ctx.params.slug;

    let type: 'none' | 'audience' | 'ledger' | 'supply' = 'none';
    let entity;

    for(const [_name, entity_item] of State.Entities.entries()) {
      if(entity_slug !== plural(entity_item.slug)) continue;

      if(entity_item instanceof Ledger) {
        type = 'ledger';
      }
      if(entity_item instanceof Supply) {
        type = 'supply';
      }

      entity = entity_item as Entity.Entity<any, any>;
    }

    if(!entity || type === 'none') return ctx.renderNotFound();

    const data = await LedgerTableData(request, entity as Ledger.Ledger<any>);

    return ctx.render({ ...data, entity });
  }
}

interface I_EntityScreen {
  entity: Entity.Entity<any>,
  entries: any[],
  meta: I_Pagination,
}

export default function EntityScreen({ data: { entity, entries, meta }}: PageProps<I_EntityScreen>) {
  if(entity instanceof Ledger) {
    return (
      <LedgerTable ledger={entity} entries={entries} total_entries={meta.total_items} meta={meta} row_config={{ show_pagination: true }} />
    )
  }
}